package com.tiyende.kash.loop.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.View
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonActivity
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.databinding.TiyendeActivityLoanGuideBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.request.IHttpCallback
import com.tiyende.kash.loop.utils.TiyendeImageUtil
import com.tiyende.kash.loop.utils.TiyendeSpannableStringUtils
import com.tiyende.kash.loop.utils.helper.TiyendeProcessHelper
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/25 18:45
 * @Annotation：线下引导页面
 */
class TiyendeLoanGuideActivity: CommonActivity() {
    private var _binding: TiyendeActivityLoanGuideBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //引导配置信息
    private var guideConfigData: JSONObject? = null

    override fun getTiyendeRootView(): View {
        _binding = TiyendeActivityLoanGuideBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnVisibility(View.INVISIBLE)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitleVisibility(View.GONE)
        setBackExit(true)

        _binding?.guideRefreshLayout?.setColorSchemeResources(R.color.theme,R.color.purple_500)
        _binding?.guideContentLayout?.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("SMS Preview Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"SMS Preview Page")
        }

        //刷新
        _binding?.guideRefreshLayout?.setOnRefreshListener {
            //刷新主流程
            publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
        }
        //下载
        _binding?.textGuideDownload?.setOnClickListener {
            openTiyendeGuideUrl()
        }
        //客服电话
        _binding?.textGuideCustomerMobile?.setOnClickListener{
            guideConfigData?.let {
                val customerMobile = it.optString("customerMobile","")
                if (customerMobile.isNotEmpty()){
                    val callIntent = Intent(Intent.ACTION_DIAL)
                    callIntent.setData(Uri.parse("tel:${customerMobile}"))
                    startActivity(callIntent)
                }
            }
        }
    }

    override fun loadTiyendeData() {
        showTiyendeLoading()
        queryTiyendeGuideLocalAction()
    }

    /**
     * 显示内容
     * type: SendSms、DownloadApk、CustomerHotline
     */
    @SuppressLint("SetTextI18n")
    private fun showTiyendeGuideConfigInfo(data: JSONObject?){
        data?.let { info ->
            _binding?.let { binding ->
                binding.guideContentLayout.visibility = View.VISIBLE
                TiyendeImageUtil.instance?.loadImageGifRes(this,binding.imgLoadApplyWaitStepMaskLoading3,R.mipmap.tiyende_step_progress_loading)
                guideConfigData = info

                binding.textGuideTitle.text = info.optString("title")
                val process = info.optJSONArray("process")
                process?.let { array ->
                    binding.guideStep1Layout.visibility = View.GONE
                    binding.guideStep2Layout.visibility = View.GONE
                    binding.guideStep3Layout.visibility = View.GONE
                    if (array.length() > 0){
                        binding.guideStep1Layout.visibility = View.VISIBLE
                        val item = array.optJSONObject(0)
                        binding.textGuideStepTitle1.text = item.optString("title")

                        binding.textGuideStepText1.visibility = View.GONE
                        val showText = item.optString("text","")
                        if (showText.isNotEmpty()){
                            binding.textGuideStepText1.visibility = View.VISIBLE
                            binding.textGuideStepText1.text = TiyendeSpannableStringUtils.changeColorAndRemoveDelimiters(showText,"[","]",Color.parseColor("#FFFF7F39"),true)
                        }
                    }

                    if (array.length() > 1){
                        binding.guideStep2Layout.visibility = View.VISIBLE
                        val item = array.optJSONObject(1)
                        binding.textGuideStepTitle2.text = item.optString("title")

                        binding.textGuideStepText2.visibility = View.GONE
                        val showText = item.optString("text","")
                        if (showText.isNotEmpty()){
                            binding.textGuideStepText2.visibility = View.VISIBLE
                            binding.textGuideStepText2.text = TiyendeSpannableStringUtils.changeColorAndRemoveDelimiters(showText,"[","]",Color.parseColor("#FFFF7F39"),true)
                        }
                    }
                    if (array.length() > 2){
                        binding.guideStep3Layout.visibility = View.VISIBLE
                        val item = array.optJSONObject(2)
                        binding.textGuideStepTitle3.text = item.optString("title")

                        binding.textGuideStepText3.visibility = View.GONE
                        val showText = item.optString("text","")
                        if (item.has("text") && item.optString("text","").isNotEmpty()){
                            binding.textGuideStepText3.visibility = View.VISIBLE
                            binding.textGuideStepText3.text = TiyendeSpannableStringUtils.changeColorAndRemoveDelimiters(showText,"{","}",Color.parseColor("#FF3ED9AB"),true)
                        }
                    }
                }

                binding.textGuideAppTitle.text = info.optString("productTitle")
                binding.textGuideLoanAmountTitle.text = info.optString("loanTitle")
                val currency = info.optString("currency")
                binding.textGuideLoanAmount.text = " $currency ${info.optString("loanAmount")} "
                binding.textGuideRiseAmount.text = "$currency ${info.optString("amount")}"

                binding.textGuideWalletTips.text = info.optString("bankTitle")
                binding.textGuideWalletTitle.text = info.optString("bankName")
                binding.textGuideWalletMobile.text = info.optString("cardNo")

                val showNotice = info.optString("notice")
                binding.textGuideNoticeMsg.text = TiyendeSpannableStringUtils.changeColorAndRemoveDelimiters(showNotice,"[","]",Color.parseColor("#FFF7A01E"),true)

                val type = info.optString("type")
                when(type){
                    "SendSms" -> {
                        binding.textGuideCustomer.visibility = View.GONE
                        binding.textGuideCustomerMobile.visibility = View.GONE
                        binding.textGuideDownload.visibility = View.GONE
                    }
                    "DownloadApk" -> {
                        binding.textGuideCustomer.visibility = View.GONE
                        binding.textGuideCustomerMobile.visibility = View.GONE

                        binding.textGuideDownload.visibility = View.VISIBLE
                        binding.textGuideDownload.text = info.optString("downloadBtnTitle")
                    }
                    else -> {//CustomerHotline
                        binding.textGuideCustomer.visibility = View.VISIBLE
                        binding.textGuideCustomerMobile.visibility = View.VISIBLE
                        binding.textGuideCustomer.text = info.optString("customerTitle")
                        binding.textGuideCustomerMobile.text = info.optString("customerMobile")

                        binding.textGuideDownload.visibility = View.GONE
                    }
                }
            }
        }
    }

    /**
     * 打开下载链接
     */
    private fun openTiyendeGuideUrl(){
        try {
            guideConfigData?.let {
                val downUrl = it.optString("url","")
                if (downUrl.isNotEmpty()){
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = Uri.parse(downUrl)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                }
            }
        } catch (e: Exception){
            showTiyendeToast(e.message)
        }
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED -> {
                hiddenTiyendeLoading()
                if (TiyendeProcessHelper.queryTiyendeGuideLocalType() == "GUIDE"){
                    queryTiyendeGuideLocalAction()
                    return
                }
                finish()
            }
            TiyendeEventData.TYPE.TIYENDE_REQUEST_ERROR -> {
                hiddenTiyendeLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 获取引导配置
     */
    private fun queryTiyendeGuideLocalAction(){
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_GUIDE_LOCAL_CONFIG_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                showTiyendeGuideConfigInfo(obj)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hiddenTiyendeLoading()
            }
        })
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        _binding?.guideRefreshLayout?.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_SMS_PREVIEW_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_SMS_PREVIEW_END)
        _binding = null
    }
}